xquery version "0.9-ml"

module "http://localhost/ns/ox"


declare namespace id="http://localhost/ns/ox/id"


define function getValue($root, $id, $node){
               (: given a datastore, an id, and  node, get the value of that node :)
	(: the data store structure is assumed to have a root collection node containing :)
	(: containing a collection of children nodes that have an id to be referenced :)
	(: $root should be a reference to the document and the root node -> doc($doc)/root_node :)
	(: $id is simply a string id. this id is expected to be in the root node provided as id:)
	(: $node is an xml element reference from where the root stops -> /child_node/child_node2/etc...
	:)

	(: create a string that will be evaluated later :)
	(: the context is passed in as $base :)
	(: this allows a concrete rference and a string value :)
	(: to be combined to access data :)
	
	let $s := fn:concat("define variable $base external
					  $base/", $node)

	for $rootNode in xdmp:eval($root)
	let $value := xdmp:eval($s,(xs:QName("base"),$rootNode) )
	where $rootNode/@id=$id
	
	return
	$value
}


define function getListOptions($node){
	for $value in fn:distinct-values(xdmp:eval($node))
	order by $value
	
	return
	<option>
	{$value}
	</option>
}

(: Specialized to pull varietals from many places :)
define function getListOptionsVarietals() {
	let $wines := fn:doc("wines.xml")/wines
	for $var in fn:distinct-values($wines//wine/varietal)
	order by $var

	return
	<option>
	{$var}
	</option>
}

(: ID Functions :)

define function getCurrentId(){
         let $wineid := fn:doc("id.xml")/id:id/id:wineid
		 return $wineid
}

define function getNewId(){
         let $wineid := fn:doc("id.xml")/id:id/id:wineid
         let $nextwineid := ($wineid) + 1
		 let $insertnode := <id:wineid>{$nextwineid}</id:wineid>
		 let $insert := xdmp:node-replace ($wineid, $insertnode)
		 return $nextwineid

		 
(: if ($wineid castable as xs:integer) then ---do id+1 as above         :)
(:                 else                                                 :)
(:         let $next-node := <id>{$next-val}</id>                       :)
(:         let $insert :=                                               :)
(:                 if ($id) then xdmp:node-replace ($id, $next-node)    :)
(:                 else xdmp:document-insert ($doc-uri, $next-node)     :)

}


